#!/usr/bin/env python
# -*- coding:utf-8 -*-


import requests
import traceback
from xawesome_mail import send_mail

def timer_checker(interval=1.0*60*60,mail_list=[],phone_list=[]):
    """
    定时检查装饰器,被装饰的函数需要返回一个{'is_change':True,'message':''}
    如果is_change 为True 就会发送邮件和短信,


    param:
    -----
    iterval : 多久运行一次被装饰的函数，每小时运行一次：1*60*60
    mail_list: 异常邮件接收列表 []
    phone_list: 异常短信接收列表

    """

    from twisted.internet import task
    from twisted.internet import reactor
    from functools import wraps

    def send_message(phone=[]):
        for ph in phone:
            data = {"functionId":"regiserverifying","body":'{"mobilePhoneNumber":"%s"}'%ph,"platCode":"H5","deviceId":"H5","appVersion":"1.0"}
            head = {"Host":"bdjh5.jd.com"}
            requests.post('http://bdjh5.jd.com/H5Promote.json',headers = head,data = data)

    def _change_moniter(func):
        @wraps(func)
        def __change_moniter(*args,**keyward):
            def change_m():
                try:
                    mes = func(*args,**keyward)
                except Exception,e:
                    err = traceback.format_exc(e)
                    send_mail('change script exception :%s'%err,mail_list)
                    send_message(phone_list)
                is_change = mes.get('is_change')
                message =  mes.get('message')
                if is_change:
                    send_message(phone_list)
                    send_mail('crawler change',message,mail_list)
            l = task.LoopingCall(change_m)
            l.start(interval)
            reactor.run()
        return __change_moniter
    return _change_moniter


if __name__ == '__main__':
    @timer_checker(2.0,['user.email@socialcredits.cn'],[])
    def test_task():
        print "test"
        return {'is_change':False,'message':'message'}
    test_task()
